module.exports = app => {
  const express = require('express')
  const upload = require('../upload')
  const customer = require('../../models/customer')
  const goodslist = require('../../models/GoodsList')
  const router = express.Router({
    mergeParams: true
  })

  router.get('/localgoodslist', async (req, res) => {
    let district = req.query.district
    console.log(district)
   const locals = await customer.find({ 'default_address': { $elemMatch: {'service':district }}})
    let area= locals['0'].default_address['0'].area
    console.log(area)
     const data = await goodslist.find({ 'status': { $ne: '下架' }, 'area': { $in: [area, "所有区域"] } })
    res.send(data)
  })
  router.get('/goodslist', async (req, res) => {
    let district = req.query.district
    const data = await goodslist.find({ 'status': { $ne: '下架' }, 'area': { $in: [district, "所有区域"] } })
    res.send(data)
  })

  //查看商品数量
  router.post('/goodslistnumber', async (req, res) => {
    var goods = JSON.parse(JSON.stringify(req.body));
    console.log(goods)
    var datas = [];
    console.log(goods)
    new Promise((resolve, reject) => {
      for (var i in goods) {
        datas.push(goods[i].id)
      }
      console.log(datas)
      resolve(datas)
    }).then(async data => {

      const date = await goodslist.find({ '_id': { $in: data } })


      res.send(date)
    })

  })

  router.post('/upgoodlist', async (req, res) => {
    var number  =JSON.parse(JSON.stringify(req.body))
    console.log(number)
number.forEach(async e => {
  var s = e.value 
  var ss = await goodslist.find({ _id: e.id })
  console.log(ss)
  ss = ss[0].number - s
  console.log(ss)
  await goodslist.updateOne({ _id: e.id }, {$set:{number:ss}})
});
 res.send('ok')
  })


  router.put('/goodscart', async (req, res) => {
    const { token, shopping_cart } = req.body
    await customer.updateOne({ token: token }, { $set: { shopping_cart: shopping_cart } }, (data,err) => {
      err ? res.send('服务器错误...') : res.send(data+'ok')
    })
  })

  app.use('/api/web', router)
  // app.use('/api/rest/:resource',async(req,res,next) => {
  //     const modelName = require('inflection').classify(req.params.resource)
  //     req.Model = require(`../../models/${modelName}`)
  //     next()
  // },router)

}